package com.megvii.koala.locker;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by linyue on 16/1/8.
 */
public class NetLockerController
{
    private static final String COMMAND_OPEN = "on1";

    private static final String COMMAND_CLOSE = "off1";

    private static final int PORT = 5000;

    private DatagramSocket socket;

    private ExecutorService executorService = Executors.newCachedThreadPool();

    synchronized public void init()
    {
        try
        {
            socket = new DatagramSocket();
            socket.setSoTimeout(6000);
        }
        catch (SocketException e)
        {
            e.printStackTrace();
        }
    }

    synchronized public void openDoor(String lockerAddress)
    {
        sendCommand(lockerAddress, COMMAND_OPEN);
    }

    synchronized public void closeDoor(String lockerAddress)
    {
        sendCommand(lockerAddress, COMMAND_CLOSE);
    }

    synchronized private void sendCommand(final String lockerAddress, final String command)
    {
        executorService.submit(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    InetAddress serverAddress = InetAddress.getByName(lockerAddress);
                    byte[] data = command.getBytes();
                    DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress,
                            PORT);
                    socket.send(packet);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
    }

    synchronized public void release()
    {
        if (socket != null)
        {
            try
            {
                socket.close();
            }
            catch (Exception e)
            {

            }
        }
        socket = null;
    }
}
